package com.example.mybatisplusdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.mybatisplusdemo.mapper.StoreMapper;
import com.example.mybatisplusdemo.model.domain.Favorite;
import com.example.mybatisplusdemo.mapper.FavoriteMapper;
import com.example.mybatisplusdemo.model.domain.Store;
import com.example.mybatisplusdemo.model.dto.FavoriteDTO;
import com.example.mybatisplusdemo.model.dto.PageDTO;
import com.example.mybatisplusdemo.service.IFavoriteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lxp
 * @since 2025-07-04
 */
@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements IFavoriteService {

    @Autowired
    FavoriteMapper favoriteMapper;

    @Autowired
    StoreMapper storeMapper;

    @Override
    public boolean addFavoriteStore(List<Favorite> favoriteList) {
        favoriteMapper.insertFavoriteStore(favoriteList);
        return true;
    }

    @Override
    public boolean removeFavoriteStore(Favorite favorite) {
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getUserId, favorite.getUserId())
               .eq(Favorite::getStoreId, favorite.getStoreId());
        favoriteMapper.delete(wrapper);
        return false;
    }

    @Override
    public Page<FavoriteDTO> listFavoriteByUserId(PageDTO pageDTO, Long userId) {
        Page<FavoriteDTO> page = new Page<>(pageDTO.getPageNo(), pageDTO.getPageSize());
        page = favoriteMapper.listFavoriteByUserId(page, userId);
        return page;
    }

    @Override
    public List<Store> getFavoriteShopsById(Long id) {
        // 查询用户收藏的店铺ID列表
        QueryWrapper<Favorite> query = new QueryWrapper<>();
        query.eq("user_id", id);

        List<Favorite> favorites = favoriteMapper.selectList(query);

        // 提取店铺ID集合
        List<Long> storeIds = favorites.stream()
                .map(Favorite::getStoreId)
                .collect(Collectors.toList());

        return storeMapper.selectBatchIds(storeIds);
    }
    @Override
    public boolean getFavoriteByUserStore(Long userId, Long storeId) {
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getUserId, userId)
               .eq(Favorite::getStoreId, storeId);
        Long count = favoriteMapper.selectCount(wrapper);
        return count > 0;
    }

}
